<template>
  <div>
    <!--    查询功能-->
    <div style="margin-bottom: 5px">
      <el-button type="primary" style="margin-left: 5px" @click="queryAll">查询</el-button>
      <!--      新增按钮-->
      <el-button type="primary" style="margin-left: 5px" @click="add">新增</el-button>
    </div>

    <!--    列表展示-->
    <el-table :data="departmentDetails" :header-cell-style="{ background: '#D3D3D3FF', color: '#555555' }">
      <el-table-column prop="id" label="部门详细ID" width="160">
      </el-table-column>
      <el-table-column label="部门名称" width="80">
        <template slot-scope="scope">
          <!-- {{ getdepartmentName(scope.row.name) }} -->
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column prop="description" label="部门详细介绍" width="160">
      </el-table-column>
      <el-table-column prop="brief" label="部门简单介绍" width="100">
      </el-table-column>
      <el-table-column label="轮播图" width="250" header-align="center">
        <template slot-scope="scope">
          <el-image style="width: 200px; height: 100px" :src="scope.row.image" fit="contain"
            :preview-src-list="[scope.row.image]"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="140">
      </el-table-column>
      <el-table-column prop="gmtModified" label="修改时间" width="140">
      </el-table-column>
      <el-table-column prop="operate" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red"
            title="这是一段内容确定删除吗？" @confirm="del(scope.row.id)" style="margin-left: 5px">
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="部门详细信息" :visible.sync="centerDialogVisible" width="30%" center :before-close="handleClose">
      <!--      新增部门角色信息表单-->
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item label="部门名称" prop="deptId">
          <el-select v-model="form.deptId" placeholder="请选择部门" readonly>
            <el-option v-for="item in departments" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门简介" prop="description">
          <el-col :span="30">
            <el-input type="textarea" :rows="10" v-model="form.brief"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="部门介绍" prop="description">
          <el-col :span="30">
            <el-input type="textarea" :rows="10" v-model="form.description"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="部门介绍" prop="brief">
          <el-col :span="30">
            <el-input type="textarea" :rows="5" v-model="form.brief"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="部门详细图片" prop="image">
          <el-upload class="avatar-uploader" :action="actionUrl" :show-file-list="false"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" name="file" :data="uploadData"
            :headers="headers">
            <img v-if="form.image" :src="form.image" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  querydepartmentDetailsAll,
  mod,
  add,
  del,
} from "@/api/departmentalServices/detailedDepartmentalManagement";
import { queryAll } from "@/api/departmentalServices/departmentManagement";
export default {
  // eslint-disable-next-line vue/multi-word-component-names
  name: "detailedDepartmentalManagement",
  data() {
    return {
      departmentDetails: [],
      departments: [],
      centerDialogVisible: false,
      actionUrl: 'http://42.194.233.38:8222/minioservice/minio-upload/upload',
      uploadData: {
        bucketName: 'dept' // 上传图片时的附加参数
      },
      headers: {},
      form: {
        id: "",
        brief: '',
        deptId: "",
        description: "",
        image: "",
      },
      rules: {
        deptId: [{ required: true, message: "请选择部门", trigger: "blur" }],
        image: [{ required: true, message: "请上传图片", trigger: "blur" }],
      },
    };
  },
  methods: {
    // 从 cookie 中获取 token
    getTokenFromCookie() {
      const cookies = document.cookie.split('; ');
      const token = cookies.find(row => row.startsWith('token='))?.split('=')[1];
      return token;
    },
    // 设置 headers
    setHeaders() {
      this.headers = {
        'token': this.getTokenFromCookie()
      };
    },
    //上传成功后的回调
    handleAvatarSuccess(response) {
      // 假设上传成功后，服务器返回图片的URL
      if (response.success) {
        this.form.image = response.data.url
        this.$message({
          message: "上传成功",
          type: "success",
        });
      } else {
        this.$message.error('上传失败');
      }
    },
    //限制图片的类型大小
    beforeAvatarUpload(file) {
      // 可以在这里添加文件类型和大小的校验
      const isImage = file.type.match('image/*');
      if (!isImage) {
        this.$message.error('只能上传图片文件');
      }
      return isImage;
    },
    //将展示列表的部门id换成部门名称
    getdepartmentName(deptId) {
      const depart = this.departments.find((c) => c.id === deptId);
      return depart ? depart.name : "未选择部门";
    },
    //重置表单
    resetForm() {
      this.$refs.form.resetFields();
      //将计数器的数字重置为1
      this.form.deptId = "";
      this.form.image = ""
    },

    //新增按钮
    add() {
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        this.resetForm();
      });
    },
    //修改
    mod(row) {
      this.centerDialogVisible = true;
      this.$nextTick(() => {
        //赋值到表单
        this.form.id = row.id;
        this.form.deptId = row.deptId;
        this.form.description = row.description;
        this.form.image = row.image;
        this.form.brief = row.brief;
      });
    },
    //删除
    del(id) {
      del(id).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    doMod() {
      mod(this.form.id, this.form).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
          this.resetForm();
        } else {
          this.$message({
            message: "修改失败",
            type: "error",
          });
        }
      });
    },
    doSave() {
      add(this.form).then((res) => {
        if (res.code === 20000) {
          this.$message({
            message: "增加成功",
            type: "success",
          });
          this.centerDialogVisible = false;
          this.queryAll();
          this.resetForm();
        } else {
          this.$message({
            message: "增加失败",
            type: "error",
          });
        }
      });
    },
    //提交数据到后台
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            //如果有id则修改
            this.doMod();
          } else {
            //否则增加
            this.doSave();
          }
        } else {
          this.$message({
            message: "操作失败",
            type: "error",
          });
          return false;
        }
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
        })
        .catch(() => { });
    },
    queryAll() {
      return new Promise(resolve => {
        querydepartmentDetailsAll().then((res) => {
          if (res.code === 20000) {
            this.departmentDetails = res.data.depts;
          } else {
            alert("获取数据失败");
          }
          resolve()
        });
      })
    },
    querydepartmentAll() {
      queryAll().then((res) => {
        if (res.code == 20000) {
          this.departments = res.data.depts.map((item) => ({
            id: item.id,
            name: item.name,
          }));
          this.departmentDetails.forEach(e=>{
            const deptId = this.departments.filter(es=>es.name==e.name)
            e.deptId = deptId.length ? deptId[0].id : ""
          })
          console.log(this.departmentDetails);
          
        }
      });
    },
  },
  async beforeMount() {
    await this.queryAll();
    this.querydepartmentAll();
  },
  mounted() {
    this.setHeaders();
  }
};
</script>

<style scoped>
.pagination-wrapper {
  position: fixed;
  bottom: 0;
  width: 100%;
  /*background-color: #f5f5f5;*/
  padding: 10px 20px;
  /*box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);*/
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  max-width: 800px;
  /* 设置最大宽度以避免在大屏幕上过分拉伸 */
  margin: 0 30%;
  /* 居中显示分页组件 */
}

.avatar-uploader .avatar {
  width: 150px;
  height: 150px;
  display: block;
}

.avatar-uploader .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.rotating {
  position: absolute;
  width: 585px;
  height: 100%;
  right: 0;
  top: 0;
}
</style>
